﻿using System.Collections.Generic;
using System.Linq;

namespace Wix.Win8SetupBootstrapper.ViewModels
{
    public sealed class ConfigurationViewModel : PageViewModelBase
    {
        public List<ConfigurationGroupViewModel> ConfigurationGroups { get; set; }



        public ConfigurationViewModel(RootViewModel rootViewModel)
            : base(rootViewModel)
        {
            ConfigurationGroups = new List<ConfigurationGroupViewModel>();

            foreach (var configuration in rootViewModel.Configuration.Ui.Pages.ConfigurationPage.ConfigurationDetails)
            {
                if (!string.IsNullOrEmpty(configuration.PackageIds))
                {
                    var packageIds = configuration.PackageIds.Split(',');
                    PackageItemViewModel package = null;
                    foreach (var packageId in packageIds)
                    {
                        package = this.RootViewModel.PackagesList.FirstOrDefault(e => e.PackageId == packageId);
                    }

                    if (package != null && !package.IsSelected)
                        continue;
                }

                var group = new ConfigurationGroupViewModel(configuration.Caption, configuration.Description);

                foreach (
                    var configItem in
                        configuration.WixVariables.Select(
                            wix => new ConfigurationItemViewModel(Bootstrapper, wix.Caption, wix.Name)))
                {
                    @group.ConfiguratinoItems.Add(configItem);
                }

                ConfigurationGroups.Add(group);
            }

            if (ConfigurationGroups.Count == 0)
            {
                this.RootViewModel.SetNextPage();
            }

            CanCancel = true;
            CanBack = true;
            CanNext = true;
        }
    }
}